import { clientsClaim } from 'workbox-core';
import { registerRoute } from 'workbox-routing';
import { precacheAndRoute } from 'workbox-precaching';
import { StaleWhileRevalidate, CacheFirst } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';

// 放在顶部，sw获得控制权，不然是下次打开页面获得
clientsClaim();
// 跳过等待
self.skipWaiting();

// 预请求资源，__WB_MANIFEST变量会注册webpack打包的所有项目资源文件
precacheAndRoute(self.__WB_MANIFEST);

// java-script files cache
registerRoute(
  new RegExp('.+\\.js$'),
  new StaleWhileRevalidate({
    cacheName: 'js-cache',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 60 * 60 * 24 * 365, // 60天
        maxEntries: 30,
      }),
    ],
  })
);

// css files cache
registerRoute(
  new RegExp('.+\\.css$'),
  new StaleWhileRevalidate({
    cacheName: 'css-cache',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 60 * 60 * 24 * 365, // 60天
        maxEntries: 30,
      }),
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
    ],
  })
);

// image files cache
registerRoute(
  new RegExp('.+\\.(png|jpg|jpeg|svg)$'),
  new CacheFirst({
    cacheName: 'images-cache',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 60 * 60 * 24 * 365, // 60天
        maxEntries: 30,
      }),
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
    ],
  })
);
